﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BingWallpaperCore
{
    public class TimedExecutService : BackgroundService
    {
        private readonly ILogger _logger;
        private readonly GetBingWallpaperService _getBingWallpaperService;

        public TimedExecutService(ILogger<TimedExecutService> logger
            , GetBingWallpaperService getBingWallpaperService)
        {
            _logger = logger;
            _getBingWallpaperService = getBingWallpaperService;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                _logger.LogInformation(DateTime.Now.ToString() + "获取每日必应桌面：启动");

                while (!stoppingToken.IsCancellationRequested)
                {
                    await _getBingWallpaperService.SetWallPaper();
                    await Task.Delay(18000000, stoppingToken);
                }
            }
            catch (Exception ex)
            {
                if (!stoppingToken.IsCancellationRequested)
                {
                    _logger.LogInformation(DateTime.Now.ToString() + "BackgroundService：异常" + ex.Message + ex.StackTrace);
                }
                else
                {
                    _logger.LogInformation(DateTime.Now.ToString() + "BackgroundService：停止");
                }
            }
        }


    }
}
